import logging
import os
import time
import json
import queue

from kafka import KafkaConsumer

from util.constants import KAFKA_HOST, FENGTAI_ETC_VEHICLE

real_vehicle_queue = queue.Queue(maxsize=2000)


def get_logger(log_type):
    # 第一步，创建一个logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log等级总开关
    # 第二步，创建一个handler，用于写入日志文件
    rq = str(time.strftime('%Y%m%d', time.localtime(time.time()))) + '_' + str(log_type)
    log_path = 'logs/'
    # log_path = '/opt/python' + '/logs/'
    # print('log_path', log_path)
    if not os.path.exists(log_path):
        os.mkdir(log_path)

    log_name = log_path + rq + '.log'
    logfile = log_name
    fh = logging.FileHandler(logfile)
    fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
    # 第三步，定义handler的输出格式
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    # 第四步，将logger添加到handler里面
    logger.addHandler(fh)
    return logger


logger = get_logger("realData")


# 接收自动驾驶车辆的实时数据
def receive_message_of_ETC_vehicle():
    print("接收自动驾驶车辆的实时数据", 'kafka 消费被触发')
    global real_vehicle_queue
    # 首先定义全局变量，用于在不同方法内互相通信
    consumer = KafkaConsumer(
        FENGTAI_ETC_VEHICLE,
        bootstrap_servers=KAFKA_HOST,
        auto_offset_reset='latest',
        enable_auto_commit=False
    )
    # 将消费者的偏移量设置为最后一条消息的偏移量
    """
            同步发送 数据
            :param data_li:  发送数据
            :return:
            """
    while True:
        time.sleep(0.1 / 6)
        for message in consumer:
            if message:
                try:
                    message_value = message.value.decode('utf-8')
                    vehicle_info = json.loads(message_value)
                    logger.info(vehicle_info)
                    real_vehicle_queue.put(vehicle_info, block=False)
                except Exception as e:
                    print(str(e))
